package io.renren.modules.weixin.controller;

import io.renren.common.utils.R;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;


@RestController
@RequestMapping("/weixin")
public class WeixinController {
    protected static final Logger LOGGER = LoggerFactory.getLogger(WeixinController.class);

    @Value("${renren.file.upload}")
    private String upload;


    @PostMapping("/file")
    public R wxupload(@RequestParam("file") MultipartFile file) {

        String fileName = file.getOriginalFilename();
        LOGGER.debug(fileName);
//        String path = upload + "/" + name + fileName.substring(fileName.lastIndexOf("."));

        try {
            File savefile = new File(upload + "/" + fileName);
            //判断上传文件的保存目录是否存在
//        if (!savefile.exists() && !savefile.isDirectory()) {
//            System.out.println(path+"目录不存在，需要创建");
//            //创建目录
//            savefile.mkdir();
//        }
            // FileUtils.copyInputStreamToFile()这个方法里对IO进行了自动操作，不需要额外的再去关闭IO流
            FileUtils.copyInputStreamToFile(file.getInputStream(), savefile);// 复制临时文件到指定目录下
        } catch (IOException e) {
            return R.error();
        }
        return R.ok();
    }
}
